﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using ZK = ZooKeeperNet;
using ZooKeeperNet;

using Common.Logging;

using WorkStation.Frameworks.Core;
using WorkStation.Frameworks.Core.Extensions;
using WorkStation.Frameworks.EasyBus;

namespace WorkStation.Frameworks.EasyBus.Repositories.ZooKeeper
{
    /// <summary>
    /// 会话监视器
    /// </summary>
    public class SessionChangeWatcher : IWatcher
    {
        protected IBus _bus;

        public SessionChangeWatcher(IBus bus) 
        {
            this._bus = bus;
        }

        public void Process(WatchedEvent @event)
        {
            Console.WriteLine("{0}-{1}".Fmt(DateTime.Now.ToString("yy-MM-dd HH:mm:ss"), @event.ToString()));

            this._bus.Logger.Info(@event.ToString());

            // 会话过期，当客户端失去连接后，在超时范围内重新连接服务端失败，在连接到新的服务端时会受到此事件
            // 因为 ZooKeeper 是多节点部署，所以认为 ZooKeeper 是不会当掉的。
            if (@event.State == KeeperState.Expired) 
            {
                // 在总线上发布 ZooKeeper 会话失效事件
                this._bus.Publish(new ZooKeeperSessionExpiredEvent());
            }
        }
    }

    /// <summary>
    /// ZooKeeper 会话失效事件
    /// </summary>
    public class ZooKeeperSessionExpiredEvent : Event
    { 
        
    }
}
